import 'dart:async';
import 'dart:core';
import 'package:e_reception_flutter/colors/colors.dart';
import 'package:e_reception_flutter/common_widgets/common_red_num_widget/common_red_num_widget.dart';
import 'package:e_reception_flutter/constants/constant.dart';
import 'package:e_reception_flutter/singleton/theme_repository/theme_repository.dart';
import 'package:e_reception_flutter/singleton/user_repository/bean/user_response_bean.dart';
import 'package:e_reception_flutter/singleton/user_repository/user_repository.dart';
import 'package:e_reception_flutter/ui/company/company_detail/event/refresh_company_detail_page_event.dart';
import 'package:e_reception_flutter/ui/create_user/edit_user/edit_user_page.dart';
import 'package:e_reception_flutter/ui/mypage/app_settings_page.dart';
import 'package:e_reception_flutter/ui/mypage/my_page_view_model.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/detailed_bean/mypage_proposal_total_bean.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/feedback_details_page.dart';
import 'package:e_reception_flutter/ui/mypage/mypage_attendance_ecord_widget/mypage_proposal_improvement.dart';
import 'package:e_reception_flutter/ui/punch_in_rule/event/refresh_rule_list_event.dart';
import 'package:e_reception_flutter/ui/smart_home/index_nav_page/smart_home_app_settings_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_function_view_model.dart';
import 'package:e_reception_flutter/ui/test_function/test_history_page.dart';
import 'package:e_reception_flutter/ui/test_function/test_scan_hsn_page.dart';
import 'package:e_reception_flutter/utils/app_monitoring_class.dart';
import 'package:e_reception_flutter/utils/app_overall_distinguish.dart';
import 'package:e_reception_flutter/utils/screen_utils.dart';
import 'package:e_reception_flutter/utils/vg_global_func.dart';
import 'package:e_reception_flutter/utils/vg_role_utils.dart';
import 'package:e_reception_flutter/utils/vg_string_utils.dart';
import 'package:e_reception_flutter/vg_widgets/light_annotated_region_style.dart';
import 'package:e_reception_flutter/vg_widgets/vg_image_widget/vg_cache_net_work_image.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:package_info/package_info.dart';
import 'package:vg_base/vg_arch_lib.dart';
import 'package:vg_base/vg_evnet_bus_lib.dart';

class SmartHomeMyPage extends StatefulWidget {
  @override
  _SmartHomeMyPageState createState() => _SmartHomeMyPageState();
}

class _SmartHomeMyPageState extends BaseState<SmartHomeMyPage> {
  UserDataBean _user;

  String versionName;

  String get fid => null;

  MyPageViewModel viewModel;
  TestFunctionViewModel testViewModel;

  // List<RecordsImprovementListBean> improvementListData;

  StreamSubscription _submitProposalStreamSubscription;

  AllAndUnReadCntNumber allAndUnReadCnt;

  @override
  void initState() {
    super.initState();
    viewModel = MyPageViewModel(this);
    testViewModel = TestFunctionViewModel(this);
    viewModel.getPunchInRuleCnt();
    VgEventBus.global.streamController.stream.listen((event) {
      // viewModel.getPunchInRuleCnt();
      if (event is RefreshCompanyDetailPageEvent ||
          event is ChangeCompanyEvent||event is RefreshRuleListEvent) {
        print('我的页面:${event?.toString()}');
        viewModel.getPunchInRuleCnt();
      }
    });
    _submitProposalStreamSubscription =
        VgEventBus.global.on<SubmitProposalInterfaceEventMonitor>()?.listen((event) {
          // viewModel?.getSuggestionListData();
          viewModel?.getSuggestionTotal();
        });
    viewModel?.recordsImprovementTotal?.addListener(() {
      allAndUnReadCnt = viewModel?.recordsImprovementTotal?.value;
      setState(() { });
    });
    viewModel?.getSuggestionTotal();
    _getPackageInfo();
  }

  @override
  void dispose() {
    _submitProposalStreamSubscription?.cancel();
    viewModel?.recordsImprovementTotal?.removeListener(() { });
    super.dispose();
  }

  void _getPackageInfo() async {
    PackageInfo packageInfo = await PackageInfo.fromPlatform();
    versionName = packageInfo?.version;
  }

  @override
  void didChangeDependencies() {
    _user = UserRepository.getInstance().of(context);
    super.didChangeDependencies();
  }

  @override
  Widget build(BuildContext context) {
    return LightAnnotatedRegion(
      child: Scaffold(
        backgroundColor: Color(0XFFF6F7F9),
        body: Column(
          children: <Widget>[
            GestureDetector(
              behavior: HitTestBehavior.translucent,
              onTap: () {
                if(!AppOverallDistinguish.comefromAiOrWeStudy() || (UserRepository.getInstance()?.userData?.comUser?.isSale()??false)){return;}
                EditUserPage.navigatorPush(
                    context, _user?.comUser?.fuid ?? "", fid);
              },
              child: Container(
                color: Colors.white,
                padding: EdgeInsets.only(
                  top: 20 + ScreenUtils.getStatusBarH(context),
                  bottom: 20,
                  left: 15,
                ),
                child: Row(
                  children: <Widget>[
                    ClipRRect(
                      borderRadius: BorderRadius.circular(32),
                      child: Container(
                        width: 64,
                        height: 64,
                        decoration: BoxDecoration(shape: BoxShape.circle),
                        child: VgCacheNetWorkImage(
                          showOriginEmptyStr(_user?.comUser?.putpicurl) ??
                              (_user?.comUser?.napicurl ?? ""),
                          defaultErrorType: ImageErrorType.head,
                          defaultPlaceType: ImagePlaceType.head,
                        ),
                      ),
                    ),
                    SizedBox(
                      width: 10,
                    ),
                    Expanded(
                      child: Container(
                        child: Column(
                          children: <Widget>[
                            Row(
                              children: <Widget>[
                                Text(
                                  VgStringUtils.subStringAndAppendSymbol(
                                      _user?.comUser?.name , 12,
                                      symbol: "...") ?? "",
                                  style: new TextStyle(
                                    color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                                    fontSize: 20,
                                  ),
                                ),
                                SizedBox(
                                  width: 6,
                                ),
                                Text(
                                  _user?.comUser?.nick ?? "",
                                  style: new TextStyle(
                                      color: Color(0xFF5E687C), fontSize: 12),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  _user?.comUser?.phone ?? "",
                                  style: new TextStyle(
                                      color: Color(0xFF5E687C), fontSize: 12),
                                ),
                              ],
                            ),
                            Row(
                              children: <Widget>[
                                Text(
                                  VgRoleUtils.isSuperAdmin(_user?.comUser?.roleid)
                                      ? "超级管理员"
                                      : "普通管理员",
                                  style: new TextStyle(
                                      color: Color(0xFF5E687C), fontSize: 12),
                                )
                              ],
                            )
                          ],
                        ),
                      ),
                    ),
                    Opacity(
                      opacity:(AppOverallDistinguish.comefromAiOrWeStudy() && (UserRepository.getInstance()?.userData?.comUser?.isNotSale()??true))? 1:0,
                      child: Padding(
                        padding: const EdgeInsets.all(15),
                        child: Icon(
                          Icons.arrow_forward_ios,
                          size: 14,
                          color: VgColors.INPUT_BG_COLOR,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ),
            SizedBox(
              height: 10,
            ),
            _OptionsBox(
              leftWidget: Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Image.asset(
                  'images/proposal.png',
                  width: 22,
                  height: 22,
                ),
              ),
              rightWidget: _toRedDotWidget(),
              text: "意见反馈",
              onTap: () {
                if((allAndUnReadCnt?.unreadCnt??0) > 0){
                  allAndUnReadCnt?.unreadCnt = 0;
                  MyPageFeedBackDetailsWidget.navigatorPush(context);
                  setState(() {});
                }else{
                  MyPageProposalImprovementWidget.navigatorPush(context,allAndUnReadCnt);
                }
              },
            ),
            _OptionsBox(
              leftWidget: Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Image.asset(
                  'images/app_settings.png',
                  width: 22,
                  height: 22,
                ),
              ),
              text: "设置",
              onTap: () {
                SmartHomeAppSettingsPage.navigatorPush(context,);
              },
            ),
            SizedBox(
              height: 10,
            ),
            _testWidget(),
            Spacer(),
            SizedBox(
              height: NAV_HEIGHT + 39 + ScreenUtils.getStatusBarH(context),
            ),
          ],
        ),
      ),
    );
  }


  Widget _testWidget(){
    return Visibility(
      visible: _user?.outFactoryFlg??false,
      child: GestureDetector(
        onTap: (){
          testViewModel.getUnqualifiedCount(context, (count){
            if((count??0) > 0){
              TestHistoryPage.navigatorPush(context);
            }else{
              TestScanHsnPage.navigatorPush(context);
            }
          });
        },
        child: Container(
          height: 50,
          color: ThemeRepository.getInstance().getCardBgColor_21263C(),
          alignment: Alignment.center,
          child: Row(
            children: <Widget>[
              SizedBox(
                width: 15,
              ),
              Padding(
                padding: const EdgeInsets.only(right: 15.0),
                child: Image.asset(
                  'images/icon_test.png',
                  width: 22,
                  height: 22,
                ),
              ),
              Text(
                "出厂检测",
                style: new TextStyle(
                  color: Color(0xFFD0E0F7),
                  fontSize: 15,
                ),
              ),
              SizedBox(
                width: 6,
              ),
              Image.asset(
                'images/icon_test_hint.png',
                width: 24,
                height: 14,
              ),
              Spacer(),
              Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: VgColors.INPUT_BG_COLOR,
              ),
              SizedBox(
                width: 15,
              )
            ],
          ),
        ),
      ),
    );
  }

  Widget _toRedDotWidget() {
    if(allAndUnReadCnt?.unreadCnt!=0){
      return CommonRedNumWidget(
        allAndUnReadCnt?.unreadCnt??0,
        isShowZero: false,
      );
    }else{
      return Container(
          child: (allAndUnReadCnt?.allCnt??0)==0 ?"" :Text(
            "${allAndUnReadCnt?.allCnt??0}",
            style: TextStyle(color: VgColors.INPUT_BG_COLOR),
          )
      );
    }

  }

}

class _OptionsBox extends StatelessWidget {
  final String text;

  final Widget leftWidget;
  final Widget rightWidget;
  final Widget subTextWidget;

  final Function() onTap;

  final bool showArrow;

  const _OptionsBox(
      {Key key,
        this.text,
        this.leftWidget,
        this.onTap,
        this.rightWidget,
        this.subTextWidget,
        this.showArrow = true})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onTap: onTap,
      child: Container(
        height: 50,
        color: Colors.white,
        alignment: Alignment.center,
        child: Row(
          children: <Widget>[
            SizedBox(
              width: 15,
            ),
            if (leftWidget != null) leftWidget,
            Text(
              text ?? "",
              style: new TextStyle(
                color: ThemeRepository.getInstance().getCardBgColor_21263C(),
                fontSize: 15,
              ),
            ),
            Spacer(),
            if (rightWidget != null) rightWidget,
            SizedBox(width: 9,),
            // leftWidget ?? Container(),
            if (subTextWidget != null) subTextWidget,
            Visibility(
              visible: showArrow,
              child: Icon(
                Icons.arrow_forward_ios,
                size: 14,
                color: VgColors.INPUT_BG_COLOR,
              ),
            ),
            SizedBox(
              width: 15,
            )
          ],
        ),
      ),
    );
  }
}
